package legway;

import java.io.File;
import lejos.nxt.SensorPort;
import lejos.nxt.Sound;
import lejos.nxt.UltrasonicSensor;
import lejos.robotics.subsumption.Behavior;

/**
 * A behavior that makes sure that the robot do not drive into an object. 
 * 
 * @author Kim Petersen, Andreas Koefoed-Hansen og Tim Rasmussen
 * @version Januar 2010
 */
public class AvoidFront implements Behavior {

	private static final int distance = 25;
	private static UltrasonicSensor sonic;
	private static Car car; 
	private static boolean isEnabled;

	/**
	 * @return isEnabled Whether or not the behavior is enabled.
	 */
	public static  boolean isEnabled() {
		return isEnabled;
	}

	/**
	 * @param isEnabled Enable/disable the behavior.
	 */
	public static synchronized void setEnabled(boolean isEnabled) {
		AvoidFront.isEnabled = isEnabled;
	}

	/**
	 * The AvoidFront constructor, a behavoir that makes the Legway turn away from objects. 
	 * @param ctrl The motor control parameters.
	 */
	public AvoidFront(CtrlParam ctrl) {
		sonic = new UltrasonicSensor(SensorPort.S2);
		car = new Car(ctrl);
	}


	/**
	 * Action methods, which make the Legway drive backwards and turn. 
	 */
	public void action() {
		File avoidFile = new File("avoid.wav");
		if(avoidFile.canRead())
			Sound.playSample(avoidFile);
		car.stop(1000);
		car.backward(800);
		car.stop(1000);
		car.left(1700);
		car.stop(1000);
	}

	/**
	 * No suppression required
	 */
	public void suppress() {

	}

	/**
	 * Take control iff the distance to an object is less than the required distance
	 * and the behavior is enabled.
	 */
	public boolean takeControl() {
		return (sonic.getDistance() < distance) && isEnabled;
	}

}
